<template>
  <div>
    <PageHeader
        title="购物车"
        :subtitle="`您的购物车中共有 ${cartStore.items.length} 件商品`"
    />

    <div class="container mx-auto px-4 py-6">
      <div v-if="cartStore.items.length > 0">
        <div class="bg-white rounded-lg shadow overflow-hidden">
          <div class="p-4 border-b">
            <el-checkbox
                v-model="allChecked"
            >
              全选
            </el-checkbox>
          </div>

          <div class="divide-y">
            <div
                v-for="item in cartStore.items"
                :key="item.id"
                class="p-4 flex flex-col md:flex-row md:items-center gap-4"
            >
              <div class="flex items-center gap-4">
                <el-checkbox
                    v-model="item.selected"
                    @change="updateSelection(item.id, item.selected)"
                />
                <img
                    :src="item.image"
                    :alt="item.name"
                    class="w-20 h-20 md:w-24 md:h-24 object-cover rounded"
                >
              </div>

              <div class="flex-grow">
                <h3 class="text-lg font-medium">{{ item.name }}</h3>
                <p class="text-gray-500 text-sm mt-1">{{ item.description }}</p>
              </div>

              <div class="flex flex-row md:flex-col lg:flex-row items-center justify-between md:justify-end gap-4">
                <div class="flex items-center gap-4">
                  <el-input-number
                      v-model="item.quantity"
                      :min="1"
                      :max="99"
                      size="small"
                      @change="(val) => updateQuantity(item.id, val)"
                      controls-position="right"
                  />
                  <span class="text-primary font-bold text-lg whitespace-nowrap">
                    ¥{{ item.price * item.quantity }}
                  </span>
                </div>
                <el-button
                    type="danger"
                    circle
                    @click="removeFromCart(item.id)"
                >
                  <el-icon>
                    <Delete/>
                  </el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <EmptyState
          v-else
          icon="ShoppingCart"
          message="购物车是空的"
      >
        <template #action>
          <router-link to="/products">
            <el-button type="primary" round class="mt-4">
              去购物
            </el-button>
          </router-link>
        </template>
      </EmptyState>
    </div>

    <!-- 底部结算栏 -->
    <div class="container mx-auto px-4 py-6">
      <div class="container mx-auto flex justify-between items-center">
        <div class="flex items-center gap-4">
          <div class="text-gray-600">
            合计: <span class="text-xl font-bold text-primary">¥{{ totalPrice }}</span>
          </div>
        </div>
        <el-button type="primary" :disabled="!selectedItems.length" @click="handleCheckout">
          结算 ({{ selectedItems.length }})
        </el-button>
      </div>
    </div>

    <!-- 选择地址对话框 -->
    <el-dialog
        v-model="showAddressDialog"
        title="选择收货地址"
        width="90%"
        style="max-width: 600px"
        top="15vh"
    >
      <div class="space-y-4">
        <el-empty v-if="!addresses.length" description="暂无收货地址">
          <el-button type="primary" @click="handleAddAddress">新增地址</el-button>
        </el-empty>

        <template v-else>
          <div class="mb-4 text-right">
            <el-button type="primary" @click="handleAddAddress">新增地址</el-button>
          </div>

          <el-radio-group v-model="selectedAddressId" class="w-full">
            <el-card
                v-for="address in addresses"
                :key="address.id"
                class="mb-4 cursor-pointer hover:shadow-md transition-shadow"
                :class="{ 'border-primary': selectedAddressId === address.id }"
                @click="selectedAddressId = address.id"
            >
              <div class="flex items-center">
                <el-radio :value="address.id" class="flex-1">
                  <div class="ml-2">
                    <div class="flex items-center gap-2 mb-1">
                      <span class="font-bold">{{ address.name }}</span>
                      <span class="text-gray-600">{{ address.phone }}</span>
                      <el-tag v-if="address.isDefault" type="success" size="small">默认地址</el-tag>
                    </div>
                    <p class="text-gray-600">{{ address.address }}</p>
                  </div>
                </el-radio>
              </div>
            </el-card>
          </el-radio-group>
        </template>
      </div>

      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="showAddressDialog = false">取消</el-button>
          <el-button
              type="primary"
              :disabled="!selectedAddressId && addresses.length > 0"
              @click="handleConfirmAddress"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import {Delete} from '@element-plus/icons-vue'
import {useCartStore} from '@/stores/cart'
import {useRouter} from 'vue-router'
import PageHeader from '@/components/common/PageHeader.vue'
import EmptyState from '@/components/common/EmptyState.vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {getAddresses} from "@/api/address.js";

const router = useRouter()
const cartStore = useCartStore()
const showAddressDialog = ref(false)
const selectedAddressId = ref('')

onMounted(() => {
  cartStore.initCart()
  getAddresses().then(res => {
    addresses.value = res.data.map(item => {
      return {
        ...item,
        isDefault: Boolean(item.isDefault),
        address:`${item.region.join('')}${item.detail}`
      }
    })
  })
})

// 选中的商品列表
const selectedItems = computed(() => cartStore.items.filter(item => item.selected))

// 总价
const totalPrice = computed(() => {
  return selectedItems.value.reduce((total, item) => total + item.price * item.quantity, 0)
})

// 全选状态
const allChecked = computed({
  get: () => cartStore.items.length > 0 && cartStore.items.every(item => item.selected),
  set: (val) => {
    cartStore.updateAllSelected(val)
    setTimeout(() => {
      cartStore.initCart()
    }, 100)
  }
})

const updateSelection = (id, selected) => {
  cartStore.updateSelected(id, selected)
}

const updateQuantity = (id, quantity) => {
  cartStore.updateQuantity(id, quantity)
}

const removeFromCart = (id) => {
  ElMessageBox.confirm(
      '确定要删除这个商品吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    cartStore.removeFromCart(id)
    setTimeout(() => {
      cartStore.initCart()
    }, 200)
    ElMessage.success('商品已删除')
  })
}

// 点击结算按钮
const handleCheckout = () => {
  if (!selectedItems.value.length) return

  // 如果只有一个默认地址，直接使用
  if (addresses.value.length === 1) {
    selectedAddressId.value = addresses.value[0].id
    handleConfirmAddress()
    return
  }

  // 否则显示地址选择对话框
  showAddressDialog.value = true

  // 默认选中默认地址
  const defaultAddress = addresses.value.find(addr => addr.isDefault)
  if (defaultAddress) {
    selectedAddressId.value = defaultAddress.id
  }
}

// 新增地址
const handleAddAddress = () => {
  router.push('/address')
}

// 确认选择地址
const handleConfirmAddress = () => {
  const address = addresses.value.find(addr => addr.id === selectedAddressId.value)
  if (!address) return

  // TODO: 跳转到订单确认页面，传递选中的商品和地址信息
  router.push({
    path: '/order/confirm',
    query: {
      addressId: address.id,
      items: selectedItems.value.map(item => item.id).join(',')
    }
  })

  showAddressDialog.value = false
}
// 模拟地址数据
const addresses = ref([])
</script>

<style scoped>
.el-input-number {
  width: 120px;
}

@media (max-width: 768px) {
  .el-input-number {
    width: 100px;
  }
}

/* 选中的地址卡片样式 */
.border-primary {
  border: 2px solid var(--el-color-primary);
}

/* 移动端优化 */
@media (max-width: 640px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 50px auto !important;
  }
}
</style>
